package Lobby;

import java.util.Date;

import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;

@Root
public class Player {
	@Element
	private String UserName;
	@Element
	private String Password;
	@Element
	private int Points;
	@Element
	private int PlayedGames;
	@Attribute
	private long created;
	@Attribute
	private long modified;

	Player(String UserName, String Password)	{
		this.UserName=UserName;
		this.Password=this.MD5(Password);
		this.setCreated();
		this.setModified();
	}
	
	//Use only for deserialization
	Player(String UserName,String Password,int Points,int PlayedGames,int created,int modified)	{
		this.UserName=UserName;
		this.Password=Password;
		this.Points=Points;
		this.PlayedGames=PlayedGames;
		this.created=created;
		this.modified=modified;
	}
	
	
	
	/*MD5 HashCode from http://stackoverflow.com/a/6565597*/
	public String MD5(String md5) {
		try {
			java.security.MessageDigest md = java.security.MessageDigest
					.getInstance("MD5");
			byte[] array = md.digest(md5.getBytes());
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < array.length; ++i) {
				sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100)
						.substring(1, 3));
			}
			return sb.toString();
		} catch (java.security.NoSuchAlgorithmException e) {
		}
		return null;
	}

	public String getUserName() {
		return UserName;
	}

	public void setUserName(String userName) {
		UserName = userName;
		this.setModified();
	}

	public String getPassword() {
		return Password;
	}

	public void setPassword(String password) {
		Password = this.MD5(password);
		this.setModified();
	}

	public int getPoints() {
		return Points;
	}

	public void addPoints(int points) {
		Points += points;
		this.setModified();
	}

	public int getPlayedGames() {
		return PlayedGames;
	}

	public void incrmentPlayedGames() {
		PlayedGames++;
		this.setModified();
	}

	public long getCreated() {
		return created;
	}

	private void setCreated() {
		Date Date = new Date();
		this.created = Date.getTime();
	}

	public long getModified() {
		return modified;
	}

	public void setModified() {
		Date Date = new Date();
		this.modified = Date.getTime();
	}
}
